import React, { Component } from "react";
import "./index.less";
import logo from "../../assets/images/logo.png";
import { Link, withRouter } from "react-router-dom";
import { Menu } from "antd";
import menuList from "../../config/menuConfig";
import memoryUtils from '../../utils/memoryUtils'
const { SubMenu } = Menu;

@withRouter
class index extends Component {
  getMenuNodes_map = (menuList) => {
    return menuList.map((item, index) => {
      if (!item.children) {
        return (
          <Menu.Item key={item.key} icon={item.icon}>
            <Link to={item.key}>{item.title}</Link>
          </Menu.Item>
        );
      } else {
        return (
          <SubMenu key={item.key} icon={item.icon} title={item.title}>
            {this.getMenuNodes(item.children)}
          </SubMenu>
        );
      }
    });
  };
  componentWillMount() {
    this.menuNodes = this.getMenuNodes(menuList);
  }

	hasAuth = item => {
		const key = item.key
		const menus = memoryUtils.user.role.menus
		const username = memoryUtils.user.username
    if ( username === 'admin' || item.isPublic || menus.indexOf( key ) !== -1 ) {
      return true;
    } else if(item.children){ 
      return  !!item.children.find(child=>menus.indexOf(child.key)!==-1)
    }
		return false
	}
  getMenuNodes = (menuList) => {
    const path = this.props.location.pathname;
    return menuList.reduce((pre, item) => {
		//
		if (this.hasAuth(item)) { 
			if (!item.children) {
        pre.push(
          <Menu.Item key={item.key} icon={item.icon}>
            <Link to={item.key}>{item.title}</Link>
          </Menu.Item>
        );
      } else {
        const cItem = item.children.find( cItem => path.indexOf(cItem.key) === 0 );
        if ( cItem ) {
          this.openKey = item.key;
        }

        pre.push(
          <SubMenu key={item.key} icon={item.icon} title={item.title}>
            {this.getMenuNodes(item.children)}
          </SubMenu>
        );
      }
		}

      
      return pre;
    }, []);
  };

  render() {
    // console.log(this.props);
    const path = this.props.location.pathname;
    const openKey = this.openKey;
    const menuNodes = this.getMenuNodes(menuList);
    return (
      <div className="left-nav">
        <Link to="/" className="left-nav-header">
          {/* <img src={logo} alt="logo" /> */}
          <h1>后台管理系统</h1>
        </Link>
        <Menu
          //默认选中
          selectedKeys={[path]}
          defaultOpenKeys={[openKey]}
          mode="inline"
          theme="dark"
        >
          {menuNodes}
        </Menu>
      </div>
    );
  }
}

export default index;
